﻿/*
 * The MIT License (MIT)
 * 
 * Copyright (c) 2012 Junhua
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 * documentation files (the "Software"), to deal in the Software without restriction, including without 
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions
 * of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */

namespace Avatar.Schedule
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;

    internal class ParallelScheduler : ITaskScheduler
    {
        ScheduleState status;
        public ScheduleState State
        {
            get { return status; }
            set
            {
                if (status != value)
                {
                    status = value;
                    if (StateChanged != null)
                    {
                        StateChanged(this, new StateChangedArgs(status));
                        if (value == ScheduleState.Done)
                        {
                            status = ScheduleState.Ready;
                        }
                    }
                }
            }
        }

        public bool Canceled
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

        Dictionary<ITask, Timer> tasks;

        public ParallelScheduler()
        {
            tasks = new Dictionary<ITask, Timer>();
            status = ScheduleState.Ready;
        }

        public void Schedule(ITask task)
        {
            if (task == null) { return; }

            lock (tasks)
            {
                if (task.IsUnique)
                {
                    if (tasks.Count > 0 && tasks.Any(x => x.Value.GetType() == task.GetType()))
                    {
                        return;
                    }
                }

                Timer timer = new Timer(OnTimerCallback, task, task.Delay, Timeout.Infinite);
                tasks.Add(task, timer);
                State = ScheduleState.Running;
            }
        }

        void OnTimerCallback(object state)
        {
            ITask task = state as ITask;
            task.Completed += OnTaskCompleted;

            try
            {
                task.Start();
            }
            catch (Exception ex)
            {
                if (Error != null)
                {
                    Error(this, new FailedEventArgs(task, ex));
                }
            }
        }

        void OnTaskCompleted(object sender, EventArgs e)
        {
            ITask task = sender as ITask;
            if (task != null)
            {
                task.Completed -= OnTaskCompleted;
            }

            lock (tasks)
            {
                tasks.Remove(task);

                if (tasks.Count == 0)
                {
                    State = ScheduleState.Done;
                }
            }
        }

        public event EventHandler<FailedEventArgs> Error;

        public event EventHandler<StateChangedArgs> StateChanged;

        public void Dispose()
        {
            tasks.Clear();
            tasks = null;
        }
    }
}
